<template>
  <el-dialog v-model="visible" :title="title + getTitle" width="80%">
    <div class="search-form">
      <el-form inline>
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item>
          <tree-select v-model="searchForm.deptId" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item>
          <duty-select v-model="searchForm.posts" placeholder="请选择职务" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="mb-10px">已选中 {{ selectedItems.length }} 人</div>

    <el-table ref="multipleTableRef" :data="list" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="姓名" prop="name" />
      <el-table-column label="部门">
        <template #default="{ row }">
          <el-tag v-if="row.dept">
            {{ row.dept.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="职务">
        <template #default="{ row }">
          <el-tag v-for="item in row.postsMiddle" :key="item.value">
            {{ item.posts.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="desc" />
      <el-table-column label="电话" prop="mobile" />
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80, 100]"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { TableInstance } from 'element-plus'
import { computed, ref, watch } from 'vue'
import Employees from '/@/api/employees'
import DutySelect from '/@/components/DutySelect/index.vue'
import TreeSelect from '/@/components/TreeSelect/index.vue'

// 类型定义
interface ApiResponse<T> {
  code: number
  result: {
    rows: T[]
    count: number
  }
}

interface Corporation {
  id: number
  name: string
  type: number
}

interface Department {
  id: number
  name: string
}

interface Post {
  id: number
  roleName: string
}

interface Player {
  id: string
  activityId: string
  employeesUserId: string
  userName: string
  userMobile: string
  userId: number
  corporationsInfo?: Corporation
  departmentsInfo?: Department
  posts?: Post[]
}

interface SearchForm {
  name: string
  mobile: string
  deptId: number | undefined
  posts: number[]
}

// Props 定义
const props = defineProps<{
  modelValue: boolean
  moduleName: string
  title: string
  formData: any
}>()

// Emits 定义
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', formData: any): void
}>()

// 状态管理
const visible = ref(props.modelValue)
const list = ref<Player[]>([])
const selectedItems = ref<Player[]>([])
const currentPage = ref(1)
const pageSize = ref(100)
const total = ref(0)
const multipleTableRef = ref<TableInstance>()
const searchForm = ref<SearchForm>({
  name: '',
  mobile: '',
  deptId: undefined,
  posts: [],
})

// 计算属性
const getTitle = computed(() => props.moduleName)

// 表格操作方法
const toggleSelection = (rows?: Player[]) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value?.toggleRowSelection(row)
    })
  } else {
    multipleTableRef.value?.clearSelection()
  }
}

const handleSelectionChange = (val: Player[]) => {
  selectedItems.value = val
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 数据操作方法
const fetchData = async () => {
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      name: searchForm.value.name,
      mobile: searchForm.value.mobile,
      deptId: searchForm.value.deptId,
      posts: searchForm.value.posts.length > 0 ? searchForm.value.posts.join(',') : undefined,
    }

    // 过滤掉空值
    const filteredParams = Object.fromEntries(Object.entries(params).filter(([_, value]) => value !== undefined && value !== ''))

    const response = await Employees.searchEmployeesApi2({ params: filteredParams })
    const { code, result } = response as unknown as ApiResponse<Player>
    if (code === 0) {
      list.value = result.rows
      total.value = result.count
    }
  } catch (error) {
    console.error('请求失败:', error)
  }
}

// 表单操作方法
const resetForm = () => {
  selectedItems.value = []
  toggleSelection()
}

const closeDialog = () => {
  visible.value = false
}

const submitForm = () => {
  const selectedIds = selectedItems.value.map((item) => item.id).join(',')
  console.log('selectedIds', selectedIds)
  emit('submit', selectedIds)
  visible.value = false
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    mobile: '',
    deptId: undefined,
    posts: [],
  }
  handleSearch()
}

// 监听属性变化
watch(
  () => props.modelValue,
  (newValue) => {
    visible.value = newValue
    if (newValue) {
      // 弹窗打开时获取最新数据
      fetchData()
    } else {
      resetForm()
    }
  }
)

watch(visible, (newValue) => {
  emit('update:modelValue', newValue)
})

watch(
  [currentPage, pageSize],
  () => {
    toggleSelection(selectedItems.value)
    fetchData()
  },
  { immediate: true }
)

defineExpose({
  visible,
  resetForm,
  submitForm,
})
</script>

<script lang="ts">
export default {
  name: 'PersonDialog',
}
</script>

<style scoped>
.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}

.el-input-number {
  width: 100%;
}

.search-form {
  margin-bottom: 20px;
}
</style>
